package com.nbstar.film.spider.font.woff.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.*;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.stream.ImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;

/**
 * Created with IntelliJ IDEA.
 *
 * @author: wangxindong
 * @date: 2018/9/6-20:02
 */
public class ImageIOUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(ImageIOUtils.class);

    private ImageIOUtils() {
    }

    public static boolean writeImage(BufferedImage image, String filename) throws IOException {
        File file = new File(filename);
        FileOutputStream output = new FileOutputStream(file);
        try {
            String formatName = filename.substring(filename.lastIndexOf('.') + 1);
            return writeImage(image, formatName, output);
        } finally {
            output.close();
        }
    }

    public static boolean writeImage(BufferedImage image, String formatName, OutputStream output) throws IOException {
        ImageOutputStream imageOutput = null;
        ImageWriter writer = null;
        try {
            Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName(formatName);
            ImageWriteParam param = null;
            IIOMetadata metadata = null;
            while (writers.hasNext()) {
                if (writer != null) {
                    writer.dispose();
                }
                writer = writers.next();
                if (writer == null) {
                    continue;
                }
                param = writer.getDefaultWriteParam();
                metadata = writer.getDefaultImageMetadata(new ImageTypeSpecifier(image), param);
                if (metadata != null
                        && !metadata.isReadOnly()
                        && metadata.isStandardMetadataFormatSupported()) {
                    break;
                }
            }
            imageOutput = ImageIO.createImageOutputStream(output);
            if (writer == null) {
                LOGGER.error("No ImageWriter found for '" + formatName + "' format");
                return false;
            }

            writer.setOutput(imageOutput);
            writer.write(null, new IIOImage(image, null, metadata), param);
        } finally {
            if (writer != null) {
                writer.dispose();
            }
            if (imageOutput != null) {
                imageOutput.close();
            }
        }
        return true;
    }

}
